package org.dy.servlet.mvc.support;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dy.servlet.mvc.Action;
import org.dy.servlet.mvc.ModelAndView;

public abstract class BaseAction implements Action {

	// if there is not request parameter required submit,return this
	protected final int NULL_PARAMETER_VALUE = -1;

	public ModelAndView process(HttpServletRequest request,
			HttpServletResponse response) {

		ModelAndView mv;
		
		try {
			mv = processInternal(request, response);
		} catch (Exception e) {
			// TODO: handle exception
			return new ErrorView(e.getMessage());
		}
		// redirect view path
		if (mv != null) {
			if (mv.getView() != null)
				mv.setView(ActionForward.getForwardView(mv.getView()));
		}

		return mv;
	}

	public abstract ModelAndView processInternal(HttpServletRequest request,
			HttpServletResponse response) throws ActionOptException;

	protected String getParameter(HttpServletRequest request, String key) {
		String s = request.getParameter(key);
		return s;
	}

	protected int getIntParameter(HttpServletRequest request, String key) {
		String s = this.getParameter(request, key);
		if (null == s || s.trim().equals(""))
			return NULL_PARAMETER_VALUE;
		char[] c = s.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] > '9' || c[i] < '0')
				return NULL_PARAMETER_VALUE;
		}
		return Integer.parseInt(s);
	}

	protected String getDefaultParameter(HttpServletRequest request,
			String key, String defaultValue) {
		return getParameter(request, key) == null ? defaultValue
				: getParameter(request, key);
	}

	protected int getDefaultIntParameter(HttpServletRequest request,
			String key, int defaultValue) {
		return getIntParameter(request, key) == -1 ? defaultValue
				: getIntParameter(request, key);
	}

	protected boolean isBlank(String str) {
		return str.trim().equals("");
	}

	protected boolean isBlankParameter(HttpServletRequest request, String str) {
		return isBlank(getParameter(request, str));
	}
	
	protected String[] getParameters(HttpServletRequest request,
			String key){
		return request.getParameterValues(key);
	}
	
	@SuppressWarnings("unchecked")
	protected Map<String,String> getSimiliarParameters(HttpServletRequest request,
			String prefix){
		Map<String,String> map = request.getParameterMap();
		Map<String,String> reMap = new HashMap<String,String>();
		
		Set<String> set = map.keySet();
		for(String key:set){
			if(key.startsWith(prefix)){
				reMap.put(key.substring(prefix.length()), request.getParameter(key));	
			}
		}
		
		return reMap;
	}

}
